﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.ModelBinding;
using OUSMS.AppLogic.BusinessLogicLayer;
using OUSMS.AppLogic.DataAccessLayer;
using OUSMS.Helpers;
using System.IO;
using AjaxControlToolkit;
using System.Net;

namespace OUSMS
{
    public partial class ModifyMotion : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                MotionsBLL motionsBLL = new MotionsBLL();
                Motions motionEntity = motionsBLL.GetMotionsByID(Convert.ToInt64(Request.QueryString["MID"]));
                titleTxtBox.Text = motionEntity.Title;
                keywordsTxtBox.Text = motionEntity.Keywords;
                backgroundTxtBox.Text = WebUtility.HtmlDecode(motionEntity.Abstract);
                contentEditor.Text = WebUtility.HtmlDecode(motionEntity.Content);
                targetTxtBox.Text = WebUtility.HtmlDecode(motionEntity.Target);
                motionTypeDDL.SelectedValue = motionEntity.Type;
                StudyAreasBLL studyAreaBLL = new StudyAreasBLL();
                studyAreaDDL.DataSource = studyAreaBLL.GetALLStuyAreas().ToList();
                studyAreaDDL.DataBind();
                studyAreaDDL.SelectedValue = motionEntity.StudyAreaID.Value.ToString();

                MotionFilesBLL motionFilesBLL = new MotionFilesBLL();
                filesGridView.DataSource = motionFilesBLL.GetMotionFilesByMotionID(Convert.ToInt64(Request.QueryString["MID"])).ToList();
                filesGridView.DataBind();

                DepartmentsBLL departmentsBLL = new DepartmentsBLL();
                IQueryable<Departments> departmentsList = departmentsBLL.GetAllDepartments();
                departmentChkboxList.DataSource = departmentsList.ToList();
                departmentChkboxList.DataBind();
                MotionDepartmentsBLL motionDepartmentBLL = new MotionDepartmentsBLL();
                for (int i = 0; i < departmentChkboxList.Items.Count; i++)
                {
                    MotionDepartments motionDepartments = motionDepartmentBLL.GetMotionDepartments(Convert.ToInt64(Request.QueryString["MID"]),
                        Convert.ToInt32(departmentChkboxList.Items[i].Value));
                    if (motionDepartments != null)
                    {
                        departmentChkboxList.Items[i].Selected = true;
                    }
                }
            }
        }


        protected void filesGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Label indexLbl = e.Row.FindControl("indexLbl") as Label;
                indexLbl.Text = (e.Row.RowIndex + 1).ToString();
            }
        }

        // 返回类型可以更改为 IEnumerable，但是为了支持
        // 分页和排序，必须添加以下参数:
        //     int maximumRows
        //     int startRowIndex
        //     out int totalRowCount
        //     string sortByExpression
        public IQueryable<MotionFiles> filesGridView_GetData([QueryString("MID")]long id)
        {
            MotionFilesBLL motionFilesBLL = new MotionFilesBLL();
            return motionFilesBLL.GetMotionFilesByMotionID(id);
        }

        protected void saveBtn_Click(object sender, EventArgs e)
        {
            try
            {
                UsersBLL usersBLL = new UsersBLL();
                Users userEntity = usersBLL.GetUserByLoginName(User.Identity.Name);
                MotionsBLL motionsBLL = new MotionsBLL();
                Motions motionEntity = motionsBLL.GetMotionsByID(Convert.ToInt64(Request.QueryString["MID"]));
                motionEntity.Title = titleTxtBox.Text.Trim();
                motionEntity.Abstract = backgroundTxtBox.Text.Trim();
                motionEntity.Content = contentEditor.Text.Trim();
                motionEntity.Target = targetTxtBox.Text.Trim();
                motionEntity.Keywords = keywordsTxtBox.Text.Trim();
                motionEntity.ProposerID = userEntity.ID;
                motionEntity.Status = "待提交";
                motionEntity.StudyAreaID = Convert.ToInt32(studyAreaDDL.SelectedValue);
                motionEntity.Type = motionTypeDDL.SelectedValue;
                MotionDepartmentsBLL motionDepartmentBLL = new MotionDepartmentsBLL();
                motionDepartmentBLL.ClearMotionDepartments(Convert.ToInt64(Request.QueryString["MID"]));
                for (int i = 0; i < departmentChkboxList.Items.Count; i++)
                {
                    if (departmentChkboxList.Items[i].Selected)
                    {
                        MotionDepartments motionDepartments = new MotionDepartments();
                        motionDepartments.DepartmentID = Convert.ToInt32(departmentChkboxList.Items[i].Value);
                        motionDepartments.MotionID = Convert.ToInt64(Request.QueryString["MID"]);
                        motionDepartmentBLL.AddMotionDepartment(motionDepartments);
                    }
                }
                motionsBLL.Save();
                Response.Redirect("MyMotionList.aspx");
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                errorMsgLbl.Text = string.Format("保存信息失败，失败原因：{0}，请报告管理员。", ex.Message);
            }
        }

        protected void submitBtn_Click(object sender, EventArgs e)
        {
            try
            {
                UsersBLL usersBLL = new UsersBLL();
                Users userEntity = usersBLL.GetUserByLoginName(User.Identity.Name);
                MotionsBLL motionsBLL = new MotionsBLL();
                Motions motionEntity = motionsBLL.GetMotionsByID(Convert.ToInt64(Request.QueryString["MID"]));
                motionEntity.Title = titleTxtBox.Text.Trim();
                motionEntity.Abstract = backgroundTxtBox.Text.Trim();
                motionEntity.Target = targetTxtBox.Text.Trim();
                motionEntity.Content = contentEditor.Text.Trim();
                motionEntity.Keywords = keywordsTxtBox.Text.Trim();
                motionEntity.ProposerID = userEntity.ID;
                motionEntity.Status = "待预审";
                motionEntity.StudyAreaID = Convert.ToInt32(studyAreaDDL.SelectedValue);
                motionEntity.Type = motionTypeDDL.SelectedValue;
                motionEntity.SumbitDateTime = DateTime.Now;
                MotionDepartmentsBLL motionDepartmentBLL = new MotionDepartmentsBLL();
                motionDepartmentBLL.ClearMotionDepartments(Convert.ToInt64(Request.QueryString["MID"]));
                for (int i = 0; i < departmentChkboxList.Items.Count; i++)
                {
                    if (departmentChkboxList.Items[i].Selected)
                    {
                        MotionDepartments motionDepartments = new MotionDepartments();
                        motionDepartments.DepartmentID = Convert.ToInt32(departmentChkboxList.Items[i].Value);
                        motionDepartments.MotionID = Convert.ToInt64(Request.QueryString["MID"]);
                        motionDepartmentBLL.AddMotionDepartment(motionDepartments);
                    }
                }
                motionsBLL.Save();
                Response.Redirect("MyMotionList.aspx");
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                errorMsgLbl.Text = string.Format("保存信息失败，失败原因：{0}，请报告管理员。", ex.Message);
            }
        }

        protected void backBtn_Click(object sender, EventArgs e)
        {
            Response.Redirect("MyMotionList.aspx");
        }

        protected void ajaxFileUpload_OnUploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
        {
            // Generate file path            
            string filePath = "/MotionPictures/" + Path.GetFileName(e.FileId) + Path.GetExtension(e.FileName);
            // Save uploaded file to the file system            
            var ajaxFileUpload = (AjaxFileUpload)sender;
            ajaxFileUpload.SaveAs(MapPath(filePath));
            // Update client with saved image path            
            e.PostedUrl = Page.ResolveUrl(filePath);
        }

        protected void uploadButton_Click(object sender, EventArgs e)
        {
            MotionFiles motionFiles = new MotionFiles();
            MotionFilesBLL motionFilesBLL = new MotionFilesBLL();
            try
            {
                if (FileUpload.HasFile)
                {
                    motionFiles.FileName = FileUpload.FileName;
                    motionFiles.UploadDateTime = DateTime.Now;
                    motionFiles.MotionID = Convert.ToInt64(Convert.ToInt64(Request.QueryString["MID"]));
                    motionFiles.Comment = FileUpload.FileName;
                    motionFiles.IsDeleted = false;

                    motionFilesBLL.CreateMotionFiles(motionFiles);

                    FileUpload.SaveAs(Request.PhysicalApplicationPath + string.Format("MotionFiles/{0}{1}", motionFiles.ID, Path.GetExtension(FileUpload.FileName)));

                    filesGridView.DataSource = motionFilesBLL.GetMotionFilesByMotionID(Convert.ToInt64(Request.QueryString["MID"])).ToList();
                    filesGridView.DataBind();
                }
            }
            catch (Exception ex)
            {
                motionFilesBLL.DeleteMotionFiles(motionFiles);
                Logger.LogError(ex);
            }
        }

        protected void deleteLinkButton_Click(object sender, EventArgs e)
        {
            try
            {
                MotionFilesBLL motionFilesBLL = new MotionFilesBLL();
                LinkButton deleteLinkButton = sender as LinkButton;
                MotionFiles motionFile = motionFilesBLL.GetMotionFileByID(Convert.ToInt64(deleteLinkButton.CommandArgument));
                motionFilesBLL.DeleteMotionFiles(motionFile);
                filesGridView.DataSource = motionFilesBLL.GetMotionFilesByMotionID(Convert.ToInt64(Request.QueryString["MID"])).ToList();
                filesGridView.DataBind();
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                errorMsgLbl.Text = string.Format("删除文件失败,失败原因:{0}", ex.Message);
                errorMsgLbl.Visible = true;
            }
        }    
    }
}